<template>
  <div class="descendant-initial-list-container">
    <!-- 操作栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="danger" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="danger" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          <span>刷新</span>
        </el-button>
        <el-button type="danger" @click="handleExport">
          <el-icon><Download /></el-icon>
          <span>导出</span>
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入单据号或耳号搜索"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        empty-text="暂无数据"
        v-loading="loading"
      >
        <el-table-column prop="documentNumber" label="单据号" align="center" width="180" />
        <el-table-column prop="initialDate" label="期初日期" align="center" width="120" />
        <el-table-column prop="sheepIds" label="耳号列表" align="center" min-width="200">
          <template #default="{ row }">
            <span>{{ formatSheepIds(row.sheepIds) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalCount" label="总数量" align="center" width="80" />
        <el-table-column prop="note" label="备注" align="center" min-width="150" />
        <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, Refresh, Download, Search } from '@element-plus/icons-vue'
import { Reads } from '@/Utils/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

// 路由
const router = useRouter()

// 搜索
const searchKeyword = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表格数据
const tableData = ref<Array<{
  documentNumber: string
  initialDate: string
  sheepIds: number[]
  totalCount: number
  note: string
  createTime: string
}>>([])

const loading = ref(false)

// 格式化耳号列表
const formatSheepIds = (sheepIds: number[]) => {
  if (!sheepIds || sheepIds.length === 0) return '-'
  if (sheepIds.length <= 3) return sheepIds.join(', ')
  return `${sheepIds.slice(0, 3).join(', ')}... 等${sheepIds.length}个`
}

// 获取列表数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    }
    
    const response = await Reads.get('/Management/GetDescendantInitialList', { params })
    console.log('获取列表数据响应:', response)
    if (response.data && response.data.code === 400) {
      const data = response.data.data || {}
      tableData.value = data.items || []
      total.value = data.total || 0
    } else {
      ElMessage.error('获取列表数据失败')
    }
  } catch (error) {
    console.error('获取列表数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 新增
const handleAdd = () => {
  router.push('/descendant-initial')
}

// 刷新
const handleRefresh = () => {
  fetchData()
  ElMessage.success('刷新成功')
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 查看
const handleView = (row: any) => {
  router.push({
    path: '/table-design/descendant-initial',
    query: { mode: 'view', documentNumber: row.documentNumber }
  })
}

// 编辑
const handleEdit = (row: any) => {
  router.push({
    path: '/table-design/descendant-initial',
    query: { mode: 'edit', documentNumber: row.documentNumber }
  })
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除单据号【${row.documentNumber}】的记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await Reads.delete(`/Management/DeleteDescendantInitial/${row.documentNumber}`)

    if (response.data && response.data.code === 400) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(response.data?.Message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.descendant-initial-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.table-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 按钮样式 */
:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  font-weight: 600 !important;
}
</style>